<?php

declare(strict_types=1);

namespace app\admin\controller;

use addons\Builder\facade\Builder;
use think\Response;
use app\common\tool\Result;
use think\facade\View;
use think\response\Json;
use app\common\model\User;
use app\common\model\Cate;
use app\common\model\ExamineTake;
use app\common\model\ExamineUser;
use app\common\model\Exam;
use app\common\model\ExamineAnswer;
use app\common\model\ExamineBank;

//该文件为自动生成，请按需修改
class Examine extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    protected string $validate = 'Examine';
    //主模型
    protected string $model = '\app\common\model\Examine';
    protected string $ExamineUser = '\app\common\model\ExamineUser';

    protected $append = ['cateText', 'typesText', 'statusText', 'timeText'];

    protected int $takeOver = 3;
    public function index(): string
    {
        return Builder::Table()
            ->autoStructure($this->model, $this->pk, 'barDemo,200')
            ->addRightButtons([
                'list_log' => [
                    'size' => '100%',
                    'title' => '考试结果',
                    'url' => url('examine/examineList')->build(),
                    'event' => '_openDrawer'
                ],
                'edit' => ['size' => '60%'],
                'delete'
            ])
            ->addTopButtons(['add' => ['size' => '60%'], 'deleteAll'])
            ->addSearch([
                ['title', '标题', 'input,Like'],
            ])
            ->fetch();
    }

    public function add($tpl = 'examine/edit')
    {
        $cate = Cate::where('pid', 0)->order('sort asc')->select();

        view::assign(
            [
                'cate' => $cate,
            ]
        );
        return parent::add($tpl); // TODO: Change the autogenerated stub
    }
    public function edit($id = '', $tpl = 'examine/edit', $info = '')
    {
        $cate = Cate::where('pid', 0)->order('sort asc')->select();
        $info = $this->model::find($id);
        view::assign(
            [
                'cate' => $cate,
            ]
        );
        return parent::edit($id, $tpl, $info); // TODO: Change the autogenerated stub
    }
    public function save($param = [], $model = true): Json
    {
        $param = $this->request->post();
        return parent::save($param, $model); // TODO: Change the autogenerated stub
    }
    /**
     * 获取用户
     */
    public  function getUser()
    {
        try {
            $param = $this->request->get();
            if (!empty($param['id'])) {
                $uidslist = ExamineUser::where([['cate', '=', $param['cate']], ['examine_id', '=', $param['id']]])->column('uid');
                $uids = ExamineTake::where(['cate' => $param['cate'], 'status' => 1, 'examine_id' => $param['id']])->column('uid');
                $uidlist = ExamineTake::where([['cate', '=', $param['cate']], ['status', '=', 1], ['examine_id', '<>', $param['id']]])->column('uid');
                $user =  User::where([['cate', '=', $param['cate']], ['cate', '<>', 0], ['id', 'not in', $uidlist]])->field('id,rname')->select();
            } else {
                $uids = ExamineTake::where(['cate' => $param['cate'], 'status' => 1])->column('uid');
                $user = User::where([['cate', '=', $param['cate']], ['cate', '<>', 0], ['id', 'not in', $uids]])->field('id,rname')->select();
            }
            // print_r($uids);die;
            if (!$user->isEmpty()) {
                foreach ($user as $k => $v) {
                    if (!empty($param['id'])) {
                        $v['check'] = in_array($v['id'], $uidslist) ? 1 : 0;
                        $v['disabled'] = in_array($v['id'], $uids) ? 1 : 0;
                    } else {
                        $v['check'] = 1;
                        $v['disabled'] = 0;
                    }
                    $user[$k] = $v;
                }
                return Result::success('获取成功', $user);
            } else {
                return Result::success('获取成功', $user);
            }
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 考试记录
     */
    public function examineList()
    {

        return Builder::Table()
            ->addColumn(['type' => 'checkbox', 'title' => '全选', 'fixed' => 'left'])
            ->addColumn(['field' => 'uid', 'title' => '考生', 'templet' => '#_userTpl'])
            ->addColumn(['field' => 'cateText', 'title' => '分类'])
            ->addColumn(['field' => 'typesText', 'title' => '考试状态'])
            ->addColumn(['field' => 'score', 'title' => '得分'])
            ->addColumn(['field' => 'score_count', 'title' => '总分'])
            ->addColumn(['field' => 'exam_time', 'title' => '考试时间'])
            ->addColumn(['fixed' => 'right', 'title' => '操作', 'align' => 'center', 'toolbar' => '#paperBarDemo', 'width' => 200])
            ->addRightButtons([
                'show_exam' => [
                    'title'       => '查看试卷',
                    'unity_title' => '考生试卷信息',
                    'url'   => url('examine/paper')->build(),
                    'w' => '60%',
                    'h' => '90%',
                    'event' => 'audit'
                ],
            ])
            ->addTopButtons(['export'])
            ->fetch('examine/examineList');
    }
    public function getExamineList(): Response
    {
        try {
            $param = request()->get();
            $map[] = ['examine_id', '=', $param['id']];
            $list = $this->ExamineUser::where($map)->with(['user'])->page(intval($param['page']), intval($param['limit']))->select();
            foreach ($list as &$v) {
                $ExamineTake = ExamineTake::where([['examine_id', '=', $param['id']], ['uid', '=', $v['uid']]])->find();
                $cateText = $this->model::where([['id', '=', $param['id']]])->append(['cateText'])->find();
                $v['score_count'] = 100;
                $v['cateText'] = $cateText['cateText'];
                $v['exam_type'] = 1;
                if (empty($ExamineTake)) {
                    $v['typesText'] = '缺考';
                    $v['score'] = 0;
                    $v['exam_time'] = '';
                    $v['paper_time']='';
                } else {
                    if ($ExamineTake['status'] == 1) {
                        $v['typesText'] = '及格';
                        $v['exam_type'] = 2;
                    } else if ($ExamineTake['status'] == 2) {
                        $v['exam_type'] = 2;
                        $v['typesText'] = '不及格';
                    } else {
                        if($cateText['end_time']>time()){
                            $v['typesText'] = '未公布';
                        }else{
                            $v['typesText'] = '缺考';
                        }
                    }
                    if($ExamineTake['paper_time'] ==0){
                        $v['paper_time']='';
                    }else{
                        $v['paper_time']=date('Y-m-d H:i:s',$ExamineTake['paper_time']);
                    }
                    $v['exam_time'] = $ExamineTake['create_time'];
                    $v['score'] = $ExamineTake['score'];
                }
            }
            $count = $this->ExamineUser::where($map)->count();
            return Result::fastReturn(['code' => 0, 'count' => $count, 'data' => $list]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     *查看试卷
     */
    public function paper($id)
    {
        $info = ExamineUser::where(['id' => $id])->find();

        $radio_id = ExamineBank::where(['examine_id' => $info->examine_id,'types'=>1,'uid'=>$info->uid])->column('exam_id');
        $check_id = ExamineBank::where(['examine_id' => $info->examine_id,'types'=>2,'uid'=>$info->uid])->column('exam_id');
        $radio_list = Exam::whereIn('id', $radio_id)->field('id,answer')->order('id asc')->select();
        foreach ($radio_list as &$v) {
            $list_exam = $this->model::getTopic($v['id']);
            $answer =ExamineAnswer::where(['examine_id' => $info->examine_id,'exam_id'=>$v['id'],'uid'=>$info->uid])->value('answer');
            foreach ($list_exam['list'] as $k=>$val){
                $list_exam['list'][$k]['check'] = 0;
                if(!empty($answer)){
                    if($answer==$v['answer'] && $val['key']==$answer){
                        $list_exam['list'][$k]['check'] = 1;
                    }
                    if($answer!=$v['answer'] && $val['key']==$answer){
                        $list_exam['list'][$k]['check'] = 2;
                    }
                }
            }
            $v->list=$list_exam;
        }
        $check_list = Exam::whereIn('id', $check_id)->field('id,answer')->order('id asc')->select();
        foreach ($check_list as &$v) {
            $list_exam = $this->model::getTopic($v['id']);
            $answer =ExamineAnswer::where(['examine_id' => $info->examine_id,'exam_id'=>$v['id'],'uid'=>$info->uid])->value('answer');
            foreach ($list_exam['list'] as &$val){
                $val['check'] = 0;
                if(!empty($answer)){
                    $answerlist = explode(',',$v['answer']);
                    $myanswerlist = explode(',',$answer);
                    if(in_array($val['key'],$answerlist) && in_array($val['key'],$myanswerlist)){
                        $val['check'] = 1;
                    }
                    if(!in_array($val['key'],$answerlist) && in_array($val['key'],$myanswerlist)){
                        $val['check'] = 2;
                    }
                }
            }
            $v->list=$list_exam;
        }
        // print('<pre>');print_r($radio_list);die;
        View::assign([
            'info'    => $info,
            'radio_list' => $radio_list,
            'check_list'=>$check_list
        ]);
        return View::fetch();
    }
}
